<?php 
namespace app\mall\model;
use think\Model;
class Store extends Model{
	protected $pk = 'id';
	protected $table = 'ys_store';
	protected $validate = [
		['title', 'require|max:50', '标题不能为空|分类名称不能超过50个字符'],
//		['logo', 'require', '请上传图片'],
        ['address', 'require', '请填写详细地址'],
	];
    protected $validate1 = [
        ['title', 'require|max:50', '标题不能为空|分类名称不能超过50个字符'],
//        ['logo', 'require', '请上传图片'],
        ['address', 'require', '请填写详细地址'],
    ];
    
	protected function initialize(){
        parent::initialize();
    }

    /**
     * 添加商品分类
     * @lingyun 2017-10-27
     */
    public function add($data){
    	$result = $this->validate($this->validate)->save($data);
    	if(!$result){
    		return ['code'=>0,'msg'=>$this->getError()];
    	}
    	return ['code'=>1,'msg'=>'添加成功！'];
    }

    /**
     * 编辑商品分类
     * @lingyun 2017-10-27
     */
    public function edit($data,$id){
        $data = $this->get_weizhi($data);
        try{
            $result =  $this->validate($this->validate1)->save($data,['id'=>$id]);
            if(false === $result){
                return ['code' => 0, 'data' => '', 'msg' => $this->getError()];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '编辑成功'];
            }
        }catch( PDOException $e){
            return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
        }
    }
    /**
     * 设置状态
     * @return [type] [description]
     */
    public function setstatus($data,$id){
    	try{
    		$result = $this->validate(false)->save($data,['id'=>$data['id']]);
    		if(false === $result){
                return ['code' => 0, 'data' => '', 'msg' => '设置失败'];
            }else{
                return ['code' => 1, 'data' => '', 'msg' => '设置成功'];
            }
    	}catch(PDOException $e){
    		return ['code' => 0, 'data' => '', 'msg' => $e->getMessage()];
    	}
    }
    /**
     * 根据商户地址获取门店地理位置
     * @return [type] [description]
     */
    private function get_weizhi($data){
        $address = $data['address'];            //详细地址
        $url='http://api.map.baidu.com/geocoder/v2/?address='.$address.'&output=json&ak=Nxx4N18bkdZmZlVpsNZA9GUUcdHc0Rf1';  
        if($result=file_get_contents($url)){        //根据地址获取地理信息 
            $result = json_decode($result,true);
            if($result['status'] == 0){
                $data['lng'] = $result['result']['location']['lng'];
                $data['lat'] = $result['result']['location']['lat'];
            }
        }  
        return $data;
    }
}
?>